
package com.zhu.salesmanagement.common;

import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

public class Actions {
    public final static boolean DEBUG = true;

    public final static int RULE_ONCE = 0;
    public final static int RULE_ADAY = 1;
    public final static int RULE_AWEEK = 2;
    public final static int RULE_AMONTH = 3;
    public final static int RULE_AYEAR = 4;

    /**
     * toast提示
     * 
     * @param activity
     * @param text
     */
    public static void toastShort(Context context, String text) {
        Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }

    /**
     * 打开浏览器
     * 
     * @param activity
     * @param url
     */
    public static void openBrowser(Activity activity, String url) {
        try {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            activity.startActivity(intent);
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

    /**
     * 分享
     * 
     * @param activity
     * @param title
     * @param content
     * @param alertTitle
     */
    public static void shareWithEmail(Activity activity, String title,
                                            String content, String alertTitle)

    {
        try {
            Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
            emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, title);
            emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, content);
            emailIntent.setType("text/plain");
            activity.startActivity(Intent.createChooser(emailIntent, alertTitle));
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

    public static final String PREF_PREFERRED_LANG = "preferred_lang";

    /**
     * @param activity
     * @return
     */
    public final static String getConfigPreferLang(Activity activity) {
        PreferenceStore mPreferenceStore = PreferenceStore.getInstance(activity);
        String mPreferLang;
        mPreferLang = mPreferenceStore.getString(PREF_PREFERRED_LANG, null);
        if (mPreferLang == null) {
            mPreferLang = getDefaultPreferLang();
        }
        return mPreferLang;
    }

    /**
     * 得到默认的本机语言
     * 
     * @private
     * @return
     */
    private static String getDefaultPreferLang() {
        Locale loc = Locale.getDefault();
        String s;
        if (loc.equals(Locale.SIMPLIFIED_CHINESE)) {
            s = "zh_CN";
        } else if (loc.equals(Locale.TRADITIONAL_CHINESE)) {
            s = "zh_TW";
        } else if (loc.equals(Locale.JAPAN)) {
            s = "jp";
        } else {
            s = "en";
        }
        return s;
    }

    /**
     * 是否连接网络
     * 
     * @return
     */
    public static boolean isNetwork(Activity activity) {
        try {
            ConnectivityManager cm = (ConnectivityManager) activity
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = cm.getActiveNetworkInfo();
            return (info != null && info.isConnected());
        } catch (Exception e) {
            Log.e(e.getMessage());
        }

        return false;
    }

    /**
     * 弹出提示
     * 
     * @param ctx
     * @param title
     * @param content
     * @param positiveResId
     * @param negativeResId
     * @param positiveListener
     * @param negativeListener
     */
    public static void alertShowDetails(Context ctx, final String title, final String content,
                                        int positiveResId, int negativeResId,
                                        OnClickListener positiveListener,
            OnClickListener negativeListener) {
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
        builder.setTitle(title);
        builder.setMessage(content);
        builder.setPositiveButton(ctx.getText(positiveResId), positiveListener);
        builder.setNegativeButton(ctx.getText(negativeResId), negativeListener);
        builder.create().show();
    }

    /**
     * //显示软键盘,控件ID可以是EditText,TextView
     * 
     * @param ctx
     * @param visible
     */
    @SuppressLint("NewApi")
    public static void hideKeyboard(Activity ctx) {
        ((InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(ctx.getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * GPS是否开启
     */
    public static boolean isGPSWorking(Context ctx) {
        LocationManager locationManager = (LocationManager) ctx
                .getSystemService(Context.LOCATION_SERVICE);
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    /**
     * 向日历中添加事件
     * 
     * @param context 上下文
     * @param eventTitle 事件标题
     * @param eventDescription 事件描述
     * @param startMillis 事件开始时间
     * @param endMillis 事件结束时间
     * @param reminderMinutus 提前时间提醒(分钟)
     */
    public static String addEvent(Context context, String eventTitle,
            String eventDescription, String noticeAddr, long startMillis, long endMillis,
            int reminderMinutus, int ruleType) {
        try {
            String calanderURL = "";
            String calanderEventURL = "";
            String calanderRemiderURL = "";

            if (Integer.parseInt(Build.VERSION.SDK) >= 8) {
                calanderURL = "content://com.android.calendar/calendars";
                calanderEventURL = "content://com.android.calendar/events";
                calanderRemiderURL = "content://com.android.calendar/reminders";
            } else {
                calanderURL = "content://calendar/calendars";
                calanderEventURL = "content://calendar/events";
                calanderRemiderURL = "content://calendar/reminders";
            }

            double calId = 0;

            // 这是数据库中视图 sql: xxxx--- FROM Events JOIN Calendars ON
            // (Events.calendar_id=Calendars._id)
            Cursor c = context.getContentResolver().query(Uri.parse(calanderURL), null, null, null,
                    null);
            if (c.moveToFirst()) {
                calId = c.getDouble(c.getColumnIndex("_id"));
                if (DEBUG) {
                    Log.e("movie to first  and id = " + calId);
                }
            } else {
                ContentValues cValues = new ContentValues();
                cValues.put("_id", calId);
                cValues.put("name", "magus");
                context.getContentResolver().insert(Uri.parse(calanderURL), cValues);
                if (DEBUG) {
                    Log.e("no first and add id to calander");
                }
            }

            ContentValues eValues = new ContentValues();
            eValues.put("dtstart", startMillis);
            eValues.put("dtend", endMillis);
            eValues.put("title", eventTitle);
            eValues.put("description", eventDescription);
            eValues.put("calendar_id", calId);
            eValues.put("hasAlarm", 1);
            eValues.put("eventTimezone", "GMT+8");
            eValues.put("eventLocation", noticeAddr);
            //
            // FREQ=MONTHLY;UNTIL=20220315T040000Z;WKST=SU;BYMONTHDAY=15
            if (ruleType != RULE_ONCE) {
                String rrule = getRule(ruleType);
                addRecurrenceRule(rrule, eValues, startMillis, endMillis);
            }

            Uri uri = context.getContentResolver().insert(
                    Uri.parse(calanderEventURL), eValues);

            String myEventsId = uri.getLastPathSegment(); // 得到当前表的_id

            ContentValues rValues = new ContentValues();
            rValues.put("event_id", myEventsId);
            rValues.put("minutes", reminderMinutus);
            rValues.put("method", 1);
            context.getContentResolver().insert(Uri.parse(calanderRemiderURL), rValues);
            if (DEBUG) {
                Log.e("success");
            }

            return myEventsId;

        } catch (Exception e) {
            return "-1";
        }
    }

    public static void addRecurrenceRule(String rrule, ContentValues values, long startMillis,
            long endMillis) {
        values.put("rrule", rrule);
        long end = endMillis;
        long start = startMillis;
        String duration = "";

        boolean isAllDay = false;
        if (end > start) {
            if (isAllDay) {
                // if it's all day compute the duration in days
                long days = (end - start + DateUtils.DAY_IN_MILLIS - 1)
                        / DateUtils.DAY_IN_MILLIS;
                duration = "P" + days + "D";
            } else {
                // otherwise compute the duration in seconds
                long seconds = (end - start) / DateUtils.SECOND_IN_MILLIS;
                duration = "P" + seconds + "S";
            }
        } else if (TextUtils.isEmpty(duration)) {

            // If no good duration info exists assume the default
            if (isAllDay) {
                duration = "P1D";
            } else {
                duration = "P3600S";
            }
        }
        // recurring events should have a duration and dtend set to null
        values.put("duration", duration);
        values.put("dtend", (Long) null);
    }

    private static String getRule(int ruleType) {
        String rrule = "";
        if (ruleType == RULE_ONCE) {

        } else if (ruleType == RULE_ADAY) {
            rrule = "FREQ=DAILY"; // FREQ=DAILY;INTERVAL=1;UNTIL=20110112T235959Z
        } else if (ruleType == RULE_AWEEK) {
            rrule = "FREQ=WEEKLY"; // FREQ=WEEKLY;BYDAY=FR,TU,TH,WE,MO;INTERVAL=1;COUNT=15
        } else if (ruleType == RULE_AMONTH) {
            rrule = "FREQ=MONTHLY"; // FREQ=MONTHLY;INTERVAL=1;UNTIL=20110531T235959Z;BYMONTHDAY=15
        } else if (ruleType == RULE_AYEAR) {
            rrule = "FREQ=YEARLY"; // FREQ=YEARLY;INTERVAL=1;UNTIL=20150106T235959Z
        }
        return rrule;
    }

    /**
     * 向日历中添加事件 提醒重复规则为每月
     * 
     * @param context 上下文
     * @param eventTitle 事件标题
     * @param eventDescription 事件描述
     * @param startMillis 事件开始时间
     * @param endMillis 事件结束时间
     * @param reminderMinutus 提前时间提醒(分钟)
     */
    public static String addEventMonth(Context context, String eventTitle,
            String eventDescription, String noticeAddr, long startMillis, long endMillis,
            int reminderMinutus) {
        try {
            String calanderURL = "";
            String calanderEventURL = "";
            String calanderRemiderURL = "";

            if (Integer.parseInt(Build.VERSION.SDK) >= 8) {
                calanderURL = "content://com.android.calendar/calendars";
                calanderEventURL = "content://com.android.calendar/events";
                calanderRemiderURL = "content://com.android.calendar/reminders";
            } else {
                calanderURL = "content://calendar/calendars";
                calanderEventURL = "content://calendar/events";
                calanderRemiderURL = "content://calendar/reminders";
            }

            double calId = 0;

            // 这是数据库中视图 sql: xxxx--- FROM Events JOIN Calendars ON
            // (Events.calendar_id=Calendars._id)
            Cursor c = context.getContentResolver().query(Uri.parse(calanderURL), null, null, null,
                    null);
            if (c.moveToFirst()) {
                calId = c.getDouble(c.getColumnIndex("_id"));
                if (DEBUG) {
                    Log.e("movie to first  and id = " + calId);
                }
            } else {
                ContentValues cValues = new ContentValues();
                cValues.put("_id", calId);
                cValues.put("name", "magus");
                context.getContentResolver().insert(Uri.parse(calanderURL), cValues);
                if (DEBUG) {
                    Log.e("no first and add id to calander");
                }
            }

            ContentValues eValues = new ContentValues();
            eValues.put("dtstart", startMillis);
            eValues.put("dtend", endMillis);
            eValues.put("title", eventTitle);
            eValues.put("description", eventDescription);
            eValues.put("calendar_id", calId);
            eValues.put("hasAlarm", 1);
            eValues.put("eventTimezone", "GMT+8");
            eValues.put("eventLocation", noticeAddr);

            // FREQ=MONTHLY;UNTIL=20220315T040000Z;WKST=SU;BYMONTHDAY=15
            Date date = new Date(startMillis);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);

            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1;
            int day = calendar.get(Calendar.DAY_OF_MONTH);

            String sMonth = month < 10 ? "0" + month : month + "";
            String sDay = day < 10 ? "0" + day : day + "";

            // FREQ=WEEKLY;COUNT=10;WKST=SU;BYDAY=TU,TH 每个星期二,星期四执行,总共执行10次,即5周
            String rrule = "FREQ=MONTHLY;UNTIL=" + year + sMonth + sDay
                    + "T000000Z;WKST=SU;BYMONTHDAY=" + day;
            if (DEBUG) {
                Log.e(rrule);
            }
            eValues.put("rrule", rrule);

            Uri uri = context.getContentResolver().insert(Uri.parse(calanderEventURL), eValues);

            String myEventsId = uri.getLastPathSegment(); // 得到当前表的_id

            ContentValues rValues = new ContentValues();
            rValues.put("event_id", myEventsId);
            rValues.put("minutes", reminderMinutus);
            rValues.put("method", 1);
            context.getContentResolver().insert(Uri.parse(calanderRemiderURL), rValues);
            if (DEBUG) {
                Log.e("success");
            }
            return myEventsId;
        } catch (Exception e) {
            return "-1";
        }
    }

    /**
     * 删除所有的事件
     * 
     * @param context
     */
    public static void delAllEvents(Context context) {
        String calanderEventURL = "";
        if (Integer.parseInt(Build.VERSION.SDK) >= 8) {
            calanderEventURL = "content://com.android.calendar/events";
        } else {
            calanderEventURL = "content://calendar/events";
        }

        ContentResolver cre = context.getContentResolver();
        int cure = cre.delete(Uri.parse(calanderEventURL), null, null);
        if (DEBUG) {
            Log.e("del events lines ==>" + cure);
        }
    }

    /**
     * 删除指定id的事件
     * 
     * @param context
     * @param id
     */
    public static void deleteEventById(Context context, String id) {
        String calanderEventURL = "";
        if (Integer.parseInt(Build.VERSION.SDK) >= 8) {
            calanderEventURL = "content://com.android.calendar/events";
        } else {
            calanderEventURL = "content://calendar/events";
        }

        ContentResolver cre = context.getContentResolver();
        int cure = cre.delete(Uri.parse(calanderEventURL), "_id=?", new String[] {
            id
        });
        if (DEBUG) {
            Log.e("del events lines ==>" + cure);
        }
    }

    /**
     * 删除指定事件
     * 
     * @param context
     * @param id
     */
    public static void deleteEvent(Context context, String where) {
        String calanderEventURL = "";
        if (Integer.parseInt(Build.VERSION.SDK) >= 8) {
            calanderEventURL = "content://com.android.calendar/events";
        } else {
            calanderEventURL = "content://calendar/events";
        }

        ContentResolver cre = context.getContentResolver();
        int cure = cre.delete(Uri.parse(calanderEventURL), where, null);
        if (DEBUG) {
            Log.e("del events lines ==>" + cure);
        }
    }

    /**
     * 显示所有日历中事件的详细
     * 
     * @param context
     * @param calanderEventURL
     */
    public static void showAllEvents(Context context) {
        String calanderURL = "";
        String calanderEventURL = "";

        if (Integer.parseInt(Build.VERSION.SDK) >= 8) {
            calanderURL = "content://com.android.calendar/calendars";
            calanderEventURL = "content://com.android.calendar/events";
        } else {
            calanderURL = "content://calendar/calendars";
            calanderEventURL = "content://calendar/events";
        }

        ContentResolver cru = context.getContentResolver();
        Cursor curu = cru.query(Uri.parse(calanderURL), null,
                /* Events._ID + "=" + myEventsId */null, null, null);
        while (curu.moveToNext()) {
            String id = curu.getString(curu.getColumnIndex("_id"));
            String name = curu.getString(curu.getColumnIndex("name"));
            System.out.println("calanderID-->" + id + ",name=" + name);
        }
        if (DEBUG) {
            System.out.println("--------show-----------");
        }

        ContentResolver cr = context.getContentResolver();
        Cursor cur = cr.query(Uri.parse(calanderEventURL), null,
                /* Events._ID + "=" + myEventsId */null, null, null);
        while (cur.moveToNext()) {
            String id = cur.getString(cur.getColumnIndex("_id"));
            String calendarId = cur.getString(cur.getColumnIndex("calendar_id"));
            String title = cur.getString(cur.getColumnIndex("title"));
            String dtstart = cur.getString(cur.getColumnIndex("dtstart"));
            String dtend = cur.getString(cur.getColumnIndex("dtend"));
            String eventLocation = cur.getString(cur.getColumnIndex("eventLocation"));
            String description = cur.getString(cur.getColumnIndex("description"));

            if (DEBUG) {
                Log.e("event =>" + id + ","
                        + calendarId + "," + title + ","
                        + dtstart + "," + dtend + "," + eventLocation + "," + description);
            }
        }
    }

    /**
     * 打开GPS设置面板
     * 
     * @param ctx Context
     * @param action <br>
     *            public static final java.lang.String ACTION_SETTINGS =
     *            "android.settings.SETTINGS";<br>
     *            public static final java.lang.String ACTION_APN_SETTINGS =
     *            "android.settings.APN_SETTINGS";<br>
     *            public static final java.lang.String
     *            ACTION_LOCATION_SOURCE_SETTINGS =
     *            "android.settings.LOCATION_SOURCE_SETTINGS";<br>
     *            public static final java.lang.String ACTION_WIRELESS_SETTINGS
     *            = "android.settings.WIRELESS_SETTINGS";<br>
     *            public static final java.lang.String
     *            ACTION_AIRPLANE_MODE_SETTINGS =
     *            "android.settings.AIRPLANE_MODE_SETTINGS";<br>
     *            public static final java.lang.String
     *            ACTION_ACCESSIBILITY_SETTINGS =
     *            "android.settings.ACCESSIBILITY_SETTINGS";<br>
     *            public static final java.lang.String ACTION_SECURITY_SETTINGS
     *            = "android.settings.SECURITY_SETTINGS";<br>
     *            public static final java.lang.String ACTION_PRIVACY_SETTINGS =
     *            "android.settings.PRIVACY_SETTINGS";<br>
     *            public static final java.lang.String ACTION_WIFI_SETTINGS =
     *            "android.settings.WIFI_SETTINGS";<br>
     *            public static final java.lang.String ACTION_WIFI_IP_SETTINGS =
     *            "android.settings.WIFI_IP_SETTINGS";<br>
     *            public static final java.lang.String ACTION_BLUETOOTH_SETTINGS
     *            = "android.settings.BLUETOOTH_SETTINGS";<br>
     *            public static final java.lang.String ACTION_DATE_SETTINGS =
     *            "android.settings.DATE_SETTINGS";<br>
     *            public static final java.lang.String ACTION_SOUND_SETTINGS =
     *            "android.settings.SOUND_SETTINGS";<br>
     *            public static final java.lang.String ACTION_DISPLAY_SETTINGS =
     *            "android.settings.DISPLAY_SETTINGS";<br>
     *            public static final java.lang.String ACTION_LOCALE_SETTINGS =
     *            "android.settings.LOCALE_SETTINGS";<br>
     *            public static final java.lang.String
     *            ACTION_INPUT_METHOD_SETTINGS =
     *            "android.settings.INPUT_METHOD_SETTINGS";<br>
     *            public static final java.lang.String
     *            ACTION_USER_DICTIONARY_SETTINGS =
     *            "android.settings.USER_DICTIONARY_SETTINGS";<br>
     *            public static final java.lang.String
     *            ACTION_APPLICATION_SETTINGS =
     *            "android.settings.APPLICATION_SETTINGS";<br>
     *            public static final java.lang.String
     *            ACTION_APPLICATION_DEVELOPMENT_SETTINGS =
     *            "android.settings.APPLICATION_DEVELOPMENT_SETTINGS";<br>
     *            public static final java.lang.String
     *            ACTION_QUICK_LAUNCH_SETTINGS =
     *            "android.settings.QUICK_LAUNCH_SETTINGS";<br>
     *            public static final java.lang.String
     *            ACTION_MANAGE_APPLICATIONS_SETTINGS =
     *            "android.settings.MANAGE_APPLICATIONS_SETTINGS";<br>
     *            public static final java.lang.String ACTION_SYNC_SETTINGS =
     *            "android.settings.SYNC_SETTINGS";<br>
     *            public static final java.lang.String ACTION_ADD_ACCOUNT =
     *            "android.settings.ADD_ACCOUNT_SETTINGS";<br>
     *            public static final java.lang.String
     *            ACTION_NETWORK_OPERATOR_SETTINGS =
     *            "android.settings.NETWORK_OPERATOR_SETTINGS";<br>
     *            public static final java.lang.String
     *            ACTION_DATA_ROAMING_SETTINGS =
     *            "android.settings.DATA_ROAMING_SETTINGS";<br>
     *            public static final java.lang.String
     *            ACTION_INTERNAL_STORAGE_SETTINGS =
     *            "android.settings.INTERNAL_STORAGE_SETTINGS";<br>
     *            public static final java.lang.String
     *            ACTION_MEMORY_CARD_SETTINGS =
     *            "android.settings.MEMORY_CARD_SETTINGS";<br>
     *            public static final java.lang.String ACTION_SEARCH_SETTINGS =
     *            "android.search.action.SEARCH_SETTINGS";<br>
     *            public static final java.lang.String
     *            ACTION_DEVICE_INFO_SETTINGS =
     *            "android.settings.DEVICE_INFO_SETTINGS";<br>
     *            public static final java.lang.String EXTRA_AUTHORITIES =
     *            "authorities";<br>
     *            public static final java.lang.String AUTHORITY = "settings";<br>
     */
    public static void openSettingIntent(Context ctx, String action) {
        Intent intent = new Intent();
        intent.setAction(action);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            ctx.startActivity(intent);
        } catch (ActivityNotFoundException ex) {
            intent.setAction(Settings.ACTION_SETTINGS);
            try {
                ctx.startActivity(intent);
            } catch (Exception e) {
            }
        }
    }

    public static boolean isSDCardMounted() {
        return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    }
}
